import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { userAPI } from "@/api/user";
import type { UserResponseData, Response, ErrorResponse } from "@/types/response";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/lib/error-handler";
import type { AxiosError } from "axios";
import { toast } from "sonner";
import { useUserStore } from "@/stores";
import { useNavigate } from "react-router-dom";

type UserResponse = Response & {
  data?: UserResponseData;
};

/**
 * useUser hooks
 */
export const useUser = () => {
  const { setUser } = useUserStore();
  const query = useQuery<UserResponse>({
    queryKey: ["user"],
    queryFn: async (): Promise<UserResponse> => {
      const response = (await userAPI.user()) as UserResponse;

      if (response.code === 200) {
        setUser(response.data as UserResponseData);
        return response;
      } else {
        throw new Error(response.message || "Get user info failed");
      }
    },
    staleTime: 5 * 60 * 1000, // 5分钟
    gcTime: 10 * 60 * 1000, // 10分钟
  });

  return {
    user: query.data?.data,
    loading: query.isLoading,
    error: query.error,
    refetch: query.refetch,
    clear: () => query.refetch(), // 使用 refetch 而不是 remove
  };
};

type UpdateUserData = {
  image?: string;
  first_name?: string;
  last_name?: string;
  address?: string;
  region?: string;
};

/**
 * useUserUpdate hook for updating user information
 */
export const useUserUpdate = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();

  const mutation = useMutation<Response, AxiosError<ErrorResponse>, UpdateUserData>({
    mutationFn: async (data: UpdateUserData) => {
      const response = await userAPI.updateUser(data);

      if (response.code === 200) {
        return response;
      } else {
        throw new Error(response.message || "Update user info failed");
      }
    },
    onSuccess: () => {
      // 使缓存失效，重新获取用户信息
      queryClient.invalidateQueries({ queryKey: ["user"] });

      toast.success(t("Success", { defaultValue: "Success" }), {
        description: t("User information updated successfully", {
          defaultValue: "User information updated successfully",
        }),
        duration: 5000,
      });
    },
    onError: (error: AxiosError<ErrorResponse>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Update failed", { defaultValue: "Update failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Update failed", { defaultValue: "Update failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Update user error:", error);
    },
  });

  return {
    updateUser: mutation.mutate,
    updateUserAsync: mutation.mutateAsync,
    isUpdating: mutation.isPending,
    error: mutation.error,
  };
};

type UpdatePasswordData = {
  current_password: string;
  new_password: string;
  confirm_password: string;
};

/**
 * usePasswordUpdate hook for updating user password
 */
export const usePasswordUpdate = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();

  const mutation = useMutation<Response, AxiosError<ErrorResponse>, UpdatePasswordData>({
    mutationFn: async (data: UpdatePasswordData) => {
      const response = await userAPI.updatePassword(data);

      if (response.code === 200) {
        return response;
      } else {
        throw new Error(response.message || "Update password failed");
      }
    },
    onSuccess: () => {
      // 使缓存失效，重新获取用户信息
      queryClient.invalidateQueries({ queryKey: ["user"] });

      toast.success(t("Success", { defaultValue: "Success" }), {
        description: t("Password updated successfully", {
          defaultValue: "Password updated successfully",
        }),
        duration: 5000,
      });
    },
    onError: (error: AxiosError<ErrorResponse>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Update failed", { defaultValue: "Update failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Update failed", { defaultValue: "Update failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Update password error:", error);
    },
  });

  return {
    updatePassword: mutation.mutate,
    updatePasswordAsync: mutation.mutateAsync,
    isUpdating: mutation.isPending,
    error: mutation.error,
  };
};

type SetPasswordData = {
  new_password: string;
  confirm_password: string;
};

/**
 * usePasswordSet hook for setting user password (for OAuth users)
 */
export const usePasswordSet = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();

  const mutation = useMutation<Response, AxiosError<ErrorResponse>, SetPasswordData>({
    mutationFn: async (data: SetPasswordData) => {
      const response = await userAPI.setPassword(data);

      if (response.code === 200) {
        return response;
      } else {
        throw new Error(response.message || "Set password failed");
      }
    },
    onSuccess: () => {
      // 使缓存失效，重新获取用户信息
      queryClient.invalidateQueries({ queryKey: ["user"] });

      toast.success(t("Success", { defaultValue: "Success" }), {
        description: t("Password set successfully", {
          defaultValue: "Password set successfully",
        }),
        duration: 5000,
      });
    },
    onError: (error: AxiosError<ErrorResponse>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Set failed", { defaultValue: "Set failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Set failed", { defaultValue: "Set failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Set password error:", error);
    },
  });

  return {
    setPassword: mutation.mutate,
    setPasswordAsync: mutation.mutateAsync,
    isSetting: mutation.isPending,
    error: mutation.error,
  };
};

type DeleteUserData = {
  password?: string;
};

/**
 * useUserDelete hook for deleting user account
 */
export const useUserDelete = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();
  const navigate = useNavigate();

  const mutation = useMutation<Response, AxiosError<ErrorResponse>, DeleteUserData>({
    mutationFn: async (data: DeleteUserData) => {
      const response = await userAPI.deleteUser(data.password);

      if (response.code === 200) {
        return response;
      } else {
        throw new Error(response.message || "Delete user failed");
      }
    },
    onSuccess: () => {
      // 清除用户相关缓存
      queryClient.removeQueries({ queryKey: ["user"] });

      toast.success(t("Success", { defaultValue: "Success" }), {
        description: t("User account deleted successfully", {
          defaultValue: "User account deleted successfully",
        }),
        duration: 5000,
      });

      // 重定向到登录页面
      setTimeout(() => {
        navigate("/cas/login");
      }, 2000);
    },
    onError: (error: AxiosError<ErrorResponse>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Delete failed", { defaultValue: "Delete failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Delete failed", { defaultValue: "Delete failed" }), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Delete user error:", error);
    },
  });

  return {
    deleteUser: mutation.mutate,
    deleteUserAsync: mutation.mutateAsync,
    isDeleting: mutation.isPending,
    error: mutation.error,
  };
};
